<script setup lang="ts">
import { debounce } from "@pureadmin/utils";
import * as echarts from "echarts";
import { onMounted, onUnmounted, ref, watchEffect } from "vue";
const charts = ref([]);
const barRef = ref();
const barWidth = 14;
const symbolSize = [barWidth, barWidth * 0.55];
const props = defineProps(["data"]);
const getSeriesData = data => {
  const arr = data.data.map((item, index) => {
    let child: any = [
      {
        type: "bar",
        name: item.nameDesc,
        data: item.value,
        stack: "zs",
        barMaxWidth: "auto",
        barWidth,
        itemStyle: {
          color: {
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            type: "linear",
            global: false,
            colorStops: [
              {
                offset: 0,
                color: data.color[index][0]
              },
              {
                offset: 1,
                color: data.color[index][1]
              }
            ]
          }
        }
      }
    ];
    const valueNotZero = item.value.find(item => item);
    if (index === 0 && valueNotZero) {
      const itemData =
        item.value?.map(val => {
          const flag = (typeof val === "number" || typeof val === "string") && ![0, "0"].includes(val);
          return {
            value: val,
            itemStyle: {
              opacity: flag ? 1 : 0
            }
          };
        }) || [];
      child = [
        ...child,

        {
          data: itemData,
          type: "pictorialBar",
          symbol: "diamond",
          symbolOffset: [0, "50%"],
          symbolSize,
          zlevel: 2,
          itemStyle: {
            normal: {
              color: data.color[index][1]
            }
          }
        },
        {
          data: itemData,
          type: "pictorialBar",
          symbolPosition: "end",
          symbol: "diamond",
          symbolOffset: [0, "-50%"],
          symbolSize,
          zlevel: 2,
          itemStyle: {
            normal: {
              borderWidth: 0,
              color: data.color[index][1]
            }
          }
        }
      ];
    } else if (valueNotZero) {
      const preData = data.data[index - 1];
      const itemData =
        item.value?.map((val, ind) => {
          const flag = (typeof val === "number" || typeof val === "string") && ![0, "0"].includes(val);
          return {
            value: Number(val) + Number(preData.value[ind]),
            itemStyle: {
              opacity: flag ? 1 : 0
            }
          };
        }) || [];
      child = [
        ...child,
        {
          data: itemData,
          type: "pictorialBar",
          symbolPosition: "end",
          symbol: "diamond",
          symbolOffset: [0, "-50%"],
          symbolSize,
          zlevel: 2,
          itemStyle: {
            normal: {
              borderWidth: 0,
              color: data.color[index][1]
            }
          }
        }
      ];
    }
    return child;
  });
  return [].concat(...arr);
};
let myChart: any = null;
const init = () => {
  if (!barRef.value) {
    return;
  }
  const chartDom = barRef.value;
  if (!myChart) {
    myChart = echarts.init(chartDom);
  }
  let option;
  const { data } = props;
  const seriseData = getSeriesData(data);
  option = {
    tooltip: {
      trigger: "axis",
      appendToBody: true,
      enterable: true,
      borderColor: "transparent",
      backgroundColor: "rgba(9,28,59,0.8)",
      padding: [4, 8],
      textStyle: {
        fontSize: 12,
        color: "rgba(255,255,255,0.9)"
      },
      extraCssText:
        "box-shadow: 0px 5px 5px -3px rgba(0,0,0,0.1), 0px 8px 10px 1px rgba(0,0,0,0.06), 0px 3px 14px 2px rgba(0,0,0,0.05);border-radius: 3px;backdrop-filter: blur(1px);",
      formatter: function (params) {
        const barData = params.filter(item => item.seriesType === "bar");
        if (barData.length === 1) {
          const item = barData[0];
          return `<div style="display:flex;align-items:center;"><div style="display:flex;align-items:center;"><div style="width: 8px;height: 8px;background:${
            item.color.colorStops[1].color
          };margin-right:4px;"></div><span style="font-weight: 400;color: rgba(255,255,255,0.9);line-height: 18px;">${params[0].axisValue}：</span></div><span style="font-weight: 600;line-height: 18px;">${item.value || item.value === 0 ? Number(item.value).toLocaleString() : "-"}</span></div>`;
        } else {
          let str = "";
          barData.forEach(item => {
            str += `<div style="display:flex;align-items:center;"><div style="display:flex;align-items:center;"><div style="width: 8px;height: 8px;background:${
              item.color.colorStops[1].color
            };margin-right:4px;"></div><span style="font-weight: 400;color: rgba(255,255,255,0.9);line-height: 18px;">${item.seriesName}：</span></div><span style="font-weight: 600;line-height: 18px;">${item.value || item.value === 0 ? Number(item.value).toLocaleString() : "-"}</span></div>`;
          });
          return `<div><div style="margin-bottom:2px">${params[0].axisValue}</div>${str}</div>`;
        }
      }
    },
    legend: {
      show: data.data.length > 1,
      itemGap: 16,
      top: 0,
      right: 0,
      itemWidth: 8,
      itemHeight: 8,
      icon: "rect",
      textStyle: {
        color: "rgba(255,255,255,0.62)",
        fontSize: 12
      }
    },
    grid: {
      containLabel: true,
      left: "6%",
      right: "5%",
      top: "20%",
      bottom: "10%"
    },
    xAxis: {
      type: "category",
      data: data.xaxis,
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(255,255,255,0.2)",
          shadowOffsetX: "20"
        }
        // symbol: ["none", "arrow"]
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        margin: 8, //刻度标签与轴线之间的距离。
        textStyle: {
          fontFamily: "Microsoft YaHei",
          color: "rgba(255,255,255,0.62)"
        },
        fontSize: 10
      }
    },
    yAxis: [
      {
        name: data.unit,
        nameTextStyle: {
          color: "rgba(255,255,255,0.62)",
          fontSize: 11
        },
        nameRotate: 1,
        type: "value",
        axisLine: {
          show: false
        },
        splitLine: {
          lineStyle: {
            // 使用深浅的间隔色
            color: ["#B5B5B5"],
            type: "dashed",
            opacity: 0.5
          }
        },
        axisLabel: {
          textStyle: {
            fontFamily: "Microsoft YaHei",
            color: "rgba(255,255,255,0.62)"
          },
          fontSize: 10
        }
      }
    ],
    series: seriseData
  };

  option && myChart.setOption(option);

  if (!charts.value.includes(myChart)) {
    charts.value.push(myChart);
  }
};
// 处理窗口大小变化
const handleResize = debounce(() => {
  // 1、图表
  charts.value.forEach(chart => {
    chart.resize();
  });
}, 60);
watchEffect(() => {
  init();
});
onMounted(() => {
  init();
  window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  charts.value.forEach(chart => {
    chart.dispose();
  });
});
</script>
<template>
  <div>
    <div ref="barRef" class="bar-chart"></div>
  </div>
</template>

<style lang="scss" scoped>
.bar-chart {
  width: 100%;
  height: 134rpx;
}
</style>
